package com.htx.zqs.blesmartmask.ui.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.htx.zqs.blesmartmask.MyApplication;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.bean.Courses;
import com.htx.zqs.blesmartmask.bean.EventBean;
import com.htx.zqs.blesmartmask.broadcastreceiver.BleBroadcastReceiver;
import com.htx.zqs.blesmartmask.custom.AutoFitTextView;
import com.htx.zqs.blesmartmask.listeners.MyClickListener;
import com.htx.zqs.blesmartmask.service.UpTimesService;
import com.htx.zqs.blesmartmask.ui.dialog.DialogUtils;
import com.htx.zqs.blesmartmask.utils.AlertUtils;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.BleUtils;
import com.htx.zqs.blesmartmask.utils.Constants;
import com.htx.zqs.blesmartmask.utils.EventBusUtil;
import com.htx.zqs.blesmartmask.utils.Logger;
import com.htx.zqs.blesmartmask.utils.MySpUtils;
import com.htx.zqs.blesmartmask.utils.RingtoneUtil;
import com.htx.zqs.blesmartmask.utils.SPUtil;
import com.htx.zqs.blesmartmask.utils.ToastUtils;
import com.htx.zqs.blesmartmask.utils.Utils;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.xw.repo.BubbleSeekBar;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;

import static com.htx.zqs.blesmartmask.utils.MySpUtils.KEY_STAR_AUTO_INCREMENT;

/**
 * Created by zhao on 2018/5/12.
 * 做面膜
 */

public class StartCourseActivity extends BaseActivity implements BubbleSeekBar.OnProgressChangedListener, CompoundButton.OnCheckedChangeListener {
    public static final String TAG = StartCourseActivity.class.getSimpleName();
    public static final String TIME_COUNT1 = "12 : 00";
    public static final String TIME_COUNT2 = "16 : 00";
    public static final String TIME_COUNT3 = "20 : 00";
    @InjectView(R.id.timeTextView)
    TextView timeTextView;
    @InjectView(R.id.runStateTextView)
    TextView runStateTextView;
    @InjectView(R.id.runStateIamgeView)
    ImageView runStateIamgeView;
    @InjectView(R.id.stopImageView)
    ImageView stopImageView;
    @InjectView(R.id.pauseImageView)
    ImageView pauseImageView;
    @InjectView(R.id.startImageView)
    ImageView startImageView;
    @InjectView(R.id.ib_back)
    ImageButton ibBack;
    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.ib_menu)
    TextView ibMenu;
    @InjectView(R.id.ll_title)
    LinearLayout llTitle;
    @InjectView(R.id.nameTextView)
    AutoFitTextView mNameTextView;
    private int mVoltageIndex;
    private int mVoltageLow = 10;
    private int mVoltageMiddle = 10;
    private int mVoltageStrong = 10;

    private Courses currentCourse;
    private KProgressHUD kProgressHUD;
    private BroadcastReceiver receiver;
    private String date;
    private String mLastCourseName;
    private Context mContext = this;
    private AlertDialog dialog;
    private AlertDialog.Builder builder;
    private int mFDCount;
    private int mVoltage;
    private RingtoneUtil mRingtoneUtil;
    private BleDevice bleDevice;
    private Map<Object, Object> mVMap;//储存电压
    private Intent mTimerIntent;

    @SuppressLint({"StringFormatInvalid", "StringFormatMatches", "CheckResult"})
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_course);
        ButterKnife.inject(this);
        bleDevice = getIntent().getParcelableExtra(Constants.BLE_DEVICE);
        startNotify(bleDevice);
        initView();
        initData();
        int aaa = getIntent().getIntExtra("aaa", 0);
        if (aaa == 1) {
            Utils.EndCourse();
        }

        int useNum = MySpUtils.getInt(MySpUtils.KEY_DEVICE_USE_NUM, -1);
        ToastUtils.show(StartCourseActivity.this, String.format(getString(R.string.device_use_num),
                useNum));

        Flowable.just("").delay(2, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        int time = MySpUtils.getInt(MySpUtils.KEY_DEVICE_USE_TIME, 0);
                        if (time >= Constants.BLE_DEVICE_COUNT_TIME) {
                            //设备使用时间达到上限400分钟
                            if (BleManager.getInstance().isConnected(bleDevice)) {
                                AlertUtils.showAlertDialog(activity, R.string.kindly_reminder_,
                                        getString(R.string.power_low_change_device));
                                BleManager.getInstance().disconnect(bleDevice);
                            }
                        } else {
                            ToastUtils.show(StartCourseActivity.this, String.format(getString(
                                    R.string.device_use_time), time));
                        }
                    }
                });

    }

    private void initData() {
        mVMap = new HashMap<>();
        mVMap = MySpUtils.getHashMapData(MySpUtils.KEY_VOLTAGE_MAP);
        if (mVMap.size() > 2) {
            mVoltageLow = (new Double((Double) mVMap.get(MySpUtils.KEY_VOLTAGE_LOW))).intValue();
            mVoltageMiddle = (new Double((Double) mVMap.get(MySpUtils.KEY_VOLTAGE_MIDDLE))).intValue();
            mVoltageStrong = (new Double((Double) mVMap.get(MySpUtils.KEY_VOLTAGE_STRONG))).intValue();

        }
        mVoltageIndex = MySpUtils.getInt(MySpUtils.KEY_VOLTAGE_POS, 0);

        mTimerIntent = new Intent(StartCourseActivity.this, UpTimesService.class);
        startService(mTimerIntent);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        tvTitle.setVisibility(View.VISIBLE);
        tvTitle.setText(R.string.start_mask);
        boolean isRunning = MySpUtils.getBoolean(KEY_STAR_AUTO_INCREMENT, false);
        String type;
        if (isRunning) {
            type = MyApplication.runningCourse.getCoursedate();
        } else {
            type = MyApplication.selectCourse.getCoursedate();
        }
        mNameTextView.setText(Utils.getCourseNameInternal(this, type));

//        requestNet();
        builder = new AlertDialog.Builder(StartCourseActivity.this).setTitle(R.string.course_start_dialog_title)
                .setMessage(getResources().getString(R.string.course_start_dialog_message));
        ibBack.setVisibility(View.VISIBLE);
        kProgressHUD = BlEUtile.getmKProgressHUD(this);
        getspDate();
        receiver = new BleBroadcastReceiver(StartCourseActivity.this);
        registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));

        mNameTextView.setOnTouchListener(new MyClickListener(new MyClickListener.MyClickCallBack() {
            @Override
            public void oneClick() {

            }

            @Override
            public void doubleClick() {
                DialogUtils.showBaseViewDialog(StartCourseActivity.this, showSelectV());
            }
        }));
        timeTextView.setOnTouchListener(new MyClickListener(new MyClickListener.MyClickCallBack() {
            @Override
            public void oneClick() {

            }

            @Override
            public void doubleClick() {
                boolean isCourseIng = MySpUtils.getBoolean(MySpUtils.KEY_STAR_AUTO_INCREMENT, false);
                if (!isCourseIng) {
                    DialogUtils.showBaseViewDialog(StartCourseActivity.this, showSelectTime());
                }
            }
        }));
    }

    private View showSelectTime() {
        View view = View.inflate(this, R.layout.dialog_select_time, null);
        ImageView ivClose = view.findViewById(R.id.iv_close);
        final TextView tvTime1 = view.findViewById(R.id.tv_time1);
        TextView tvTime2 = view.findViewById(R.id.tv_time2);
        TextView tvTime3 = view.findViewById(R.id.tv_time3);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.tv_time1:
                        timeTextView.setText(TIME_COUNT1);
                        break;
                    case R.id.tv_time2:
                        timeTextView.setText(TIME_COUNT2);
                        break;
                    case R.id.tv_time3:
                        timeTextView.setText(TIME_COUNT3);
                        break;
                }
                DialogUtils.dismiss();
            }
        };
        ivClose.setOnClickListener(onClickListener);
        tvTime1.setOnClickListener(onClickListener);
        tvTime2.setOnClickListener(onClickListener);
        tvTime3.setOnClickListener(onClickListener);
        return view;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        if (mRingtoneUtil != null) {
            mRingtoneUtil.stopShock();
            mRingtoneUtil.stopSound();
        }
        mRingtoneUtil = null;
//        for (BleDevice bleDevice : BleManager.getInstance().getAllConnectedDevice()) {
//            BleUtils.stopNotify(bleDevice);
//        }
    }

    @Override
    public void setCourseData(final BleDevice bleDevice, byte[] buffer) {
        super.setCourseData(bleDevice, buffer);
        int[] intArray = new int[buffer.length];
        for (int i = 0; i < intArray.length; i++) {
            intArray[i] = buffer[i] & 0xff;
        }
        //intArray[4] == 0 旧设备
        int index = intArray[4] == 0 ? intArray[6] : intArray[10];
        int state = intArray[11];
        if (state == 253) {
            mFDCount++;
            if (mFDCount > 1) {
                try {
                    if (builder != null) {
                        if (dialog == null || !dialog.isShowing()) {
                            dialog = builder.setNegativeButton(R.string.cancle, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dismiss();
                                    blePauseCourse();
                                }
                            }).show();
                        }
                    }
                } catch (Exception e) {
                    e.toString();
                }
            }

        } else {
            mFDCount = 0;
            String timeText = "00 : 00";

            if (state != 0) {
                currentCourse = getCourseFromIndex(index);
                if (currentCourse != null) {
                    timeText = Utils.formatTime(intArray[7] + intArray[8], intArray[9]);
                    if (timeText.equals(Constants.COURSE_END_TIME)) {
                        timeTextView.setText(timeText);
                        return;
                    }
                    timeTextView.setText(timeText);
                } else {
                    currentCourse = MyApplication.selectCourse;
                    timeText = Utils.formatTime(intArray[7] + intArray[8], intArray[9]);
                    timeTextView.setText(timeText);
                }
            } else {
                currentCourse = MyApplication.selectCourse;
                if (currentCourse != null) {
                    int totalTime = currentCourse.getTimeone() +
                            currentCourse.getTimetwo() + currentCourse.getTimethree();
                    if (totalTime < 20) {
                        totalTime = 20;
                    }
                    timeText = totalTime + " : 00";
                }
            }

            Timber.e("设备mac：" + bleDevice.getMac() + "===做课程中time：" + timeText);

            if (state == 0) {
                runStateTextView.setText(getResources().getString(R.string.un_runing));
                runStateIamgeView.setImageResource(R.mipmap.run);
                stopImageView.setEnabled(false);
                pauseImageView.setEnabled(false);
                startImageView.setEnabled(true);
                MyApplication.bluetoothState = 0;
            } else if (state == 0xfe) {
                runStateTextView.setText(getResources().getString(R.string.error_pause));
                runStateIamgeView.setImageResource(R.mipmap.run);
                stopImageView.setEnabled(true);
                pauseImageView.setEnabled(false);
                startImageView.setEnabled(true);
                MyApplication.bluetoothState = 0xfe;
            } else if (state == 0xff) {
                runStateTextView.setText(getResources().getString(R.string.pausing));
                runStateIamgeView.setImageResource(R.mipmap.run);
                stopImageView.setEnabled(true);
                pauseImageView.setEnabled(false);
                startImageView.setEnabled(true);
                MyApplication.bluetoothState = 0xff;
            } else if (state == 1) {
                runStateTextView.setText(getResources().getString(R.string.runing));
                Glide.with(getApplication()).load(R.mipmap.running).into(runStateIamgeView);
                stopImageView.setEnabled(true);
                pauseImageView.setEnabled(true);
                startImageView.setEnabled(false);
                MyApplication.bluetoothState = 1;
            }
        }
        dismiss();
    }

    private void dismiss() {
        if (kProgressHUD != null && kProgressHUD.isShowing()) {
            kProgressHUD.dismiss();
        }
    }

    public Courses getCourseFromIndex(int index) {
        if (MyApplication.courses == null || MyApplication.courses.size() == 0) {
            return null;
        } else {
            for (Courses course : MyApplication.courses) {
                if (course.getId() == index) {
                    return course;
                }
            }
            return null;
        }
    }

    @OnClick({R.id.stopImageView, R.id.pauseImageView, R.id.startImageView, R.id.ib_back, R.id.layout_voltage})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                finish();
                break;
            case R.id.layout_voltage:
                //调整电压
//                DialogUtils.showBaseViewDialog(this, showSelectV());
                break;
            case R.id.stopImageView:
                if (stopImageView.isEnabled()) {
                    kProgressHUD.show();
                    bleStopCourse();
                }
                Log.e("cli", "onViewClicked: 我点你了吗 stop");
                break;
            case R.id.pauseImageView:
                if (pauseImageView.isEnabled()) {
                    if (MyApplication.bluetoothState == Contants.STATE_RUNING) {
                        kProgressHUD.show();
                        blePauseCourse();
                    }
                }
                break;
            case R.id.startImageView:
                if (startImageView.isEnabled()) {
                    start();
                } else {
                    stopImageView.setEnabled(true);
                    pauseImageView.setEnabled(true);
                }
                break;
        }
    }

    private TextView tvLow;
    private TextView tvMiddle;
    private TextView tvStrong;
    private BubbleSeekBar sbLow;
    private BubbleSeekBar sbMiddle;
    private BubbleSeekBar sbStrong;
    private CheckBox cbLow;
    private CheckBox cbMiddle;
    private CheckBox cbStrong;

    private View showSelectV() {
        View view = View.inflate(this, R.layout.dialog_select_voltage, null);
        ImageView ivClose = view.findViewById(R.id.iv_close);
        tvLow = view.findViewById(R.id.tv_low);
        tvMiddle = view.findViewById(R.id.tv_middle);
        tvStrong = view.findViewById(R.id.tv_strong);
        sbLow = view.findViewById(R.id.sb_low);
        sbMiddle = view.findViewById(R.id.sb_middle);
        sbStrong = view.findViewById(R.id.sb_strong);
        cbLow = view.findViewById(R.id.cb_low);
        cbMiddle = view.findViewById(R.id.cb_middle);
        cbStrong = view.findViewById(R.id.cb_strong);


        showLowV(mVoltageLow);
        showMiddleV(mVoltageMiddle);
        showStrongV(mVoltageStrong);
        sbLow.setProgress(mVoltageLow);
        sbMiddle.setProgress(mVoltageMiddle);
        sbStrong.setProgress(mVoltageStrong);

        cbLow.setOnCheckedChangeListener(this);
        cbMiddle.setOnCheckedChangeListener(this);
        cbStrong.setOnCheckedChangeListener(this);
        sbLow.setOnProgressChangedListener(this);
        sbMiddle.setOnProgressChangedListener(this);
        sbStrong.setOnProgressChangedListener(this);
        switch (mVoltageIndex) {
            case 0:
                cbLow.setChecked(true);
                break;
            case 1:
                cbMiddle.setChecked(true);
                break;
            case 2:
                cbStrong.setChecked(true);
                break;
        }
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.dismiss();
            }
        });
        return view;
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_low:
                sbMiddle.setClickable(false);
                sbMiddle.setEnabled(false);
                sbStrong.setClickable(false);
                sbStrong.setEnabled(false);
                if (isChecked) {
                    cbMiddle.setChecked(false);
                    cbStrong.setChecked(false);
                    MySpUtils.putInt(MySpUtils.KEY_VOLTAGE_POS, 0);
                    mVoltageIndex = 0;
                }
                sbLow.setClickable(isChecked);
                sbLow.setEnabled(isChecked);
                break;
            case R.id.cb_middle:
                sbLow.setClickable(false);
                sbLow.setEnabled(false);
                sbStrong.setClickable(false);
                sbStrong.setEnabled(false);
                if (isChecked) {
                    cbLow.setChecked(false);
                    cbStrong.setChecked(false);
                    MySpUtils.putInt(MySpUtils.KEY_VOLTAGE_POS, 1);
                    mVoltageIndex = 1;
                }
                sbMiddle.setClickable(isChecked);
                sbMiddle.setEnabled(isChecked);
                break;
            case R.id.cb_strong:
                sbLow.setClickable(false);
                sbLow.setEnabled(false);
                sbMiddle.setClickable(false);
                sbMiddle.setEnabled(false);
                if (isChecked) {
                    cbLow.setChecked(false);
                    cbMiddle.setChecked(false);
                    MySpUtils.putInt(MySpUtils.KEY_VOLTAGE_POS, 2);
                    mVoltageIndex = 2;
                }
                sbStrong.setClickable(isChecked);
                sbStrong.setEnabled(isChecked);
                break;
        }
    }

    private void showLowV(int progress) {
        DecimalFormat format = new DecimalFormat("##0.00");
        String low = format.format((float) progress * 3.15 / sbLow.getMax() + 4.85);
        tvLow.setText(low + "v");
    }

    private void showMiddleV(int progress) {
        DecimalFormat format = new DecimalFormat("##0.00");
        String middle = format.format((float) progress * 3.84 / sbMiddle.getMax() + 8.19);
        tvMiddle.setText(middle + "v");
    }

    private void showStrongV(int progress) {
        DecimalFormat format = new DecimalFormat("##0.00");
        String strong = format.format((float) progress * 3.82 / sbStrong.getMax() + 12.18);
        tvStrong.setText(strong + "v");
    }

    //0-100
    @SuppressLint("SetTextI18n")
    @Override
    public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
        switch (bubbleSeekBar.getId()) {
            case R.id.sb_low:
                showLowV(progress);
                break;
            case R.id.sb_middle:
                showMiddleV(progress);
                break;
            case R.id.sb_strong:
                showStrongV(progress);
                break;
        }
    }

    @Override
    public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
        switch (bubbleSeekBar.getId()) {
            case R.id.sb_low:
                mVMap.put(MySpUtils.KEY_VOLTAGE_LOW, progress);
                mVMap.put(MySpUtils.KEY_VOLTAGE_MIDDLE, mVoltageMiddle);
                mVMap.put(MySpUtils.KEY_VOLTAGE_STRONG, mVoltageStrong);
                mVoltageLow = progress;

                break;
            case R.id.sb_middle:
                mVMap.put(MySpUtils.KEY_VOLTAGE_LOW, mVoltageLow);
                mVMap.put(MySpUtils.KEY_VOLTAGE_MIDDLE, progress);
                mVMap.put(MySpUtils.KEY_VOLTAGE_STRONG, mVoltageStrong);
                mVoltageMiddle = progress;
                progress = (int) (sbLow.getMax() + progress) + 1;
                break;
            case R.id.sb_strong:
                mVMap.put(MySpUtils.KEY_VOLTAGE_LOW, mVoltageLow);
                mVMap.put(MySpUtils.KEY_VOLTAGE_MIDDLE, mVoltageMiddle);
                mVMap.put(MySpUtils.KEY_VOLTAGE_STRONG, progress);
                mVoltageStrong = progress;
                progress = (int) (sbLow.getMax() + sbMiddle.getMax() + progress) + 1 + 1;
                break;
        }
        Timber.e("progress:" + progress);
        MySpUtils.putHashMapData(MySpUtils.KEY_VOLTAGE_MAP, mVMap);
        bleChangVoltage(progress);
    }

    @Override
    public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {

    }

    private int mProgress;

    private void start() {
        if (MyApplication.bluetoothState != Contants.STATE_RUNING) {
            if (MyApplication.bluetoothState == Contants.STATE_NO_RUN) {
                String[] lesson = new String[]{getResources().getString(R.string.weak),
                        getResources().getString(R.string.medium), getResources().getString(R.string.high)};
                new AlertDialog.Builder(StartCourseActivity.this)
                        .setTitle(R.string.dialog_title_choose)
                        .setItems(lesson, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                mVoltageIndex = which;
                                switch (which) {
                                    case 0:
                                        mProgress = (int) (mVoltageLow * ((float) 100 / 115));
                                        SPUtil.put(MyApplication.appContext, "setTing", 1, "setTing");
                                        break;
                                    case 1:
                                        mProgress = (int) ((mVoltageMiddle + 40) * ((float) 100 / 115));
                                        SPUtil.put(MyApplication.appContext, "setTing", 2, "setTing");
                                        break;
                                    case 2:
                                        mProgress = (int) ((mVoltageStrong + 80) * ((float) 100 / 115));
                                        SPUtil.put(MyApplication.appContext, "setTing", 3, "setTing");
                                        break;
                                }
                                Log.e("开始做面膜 mProgress:====", "====" + mProgress);
                                mVoltage = 0;
                                if (MyApplication.limitSeconds < Contants.LIMIT_TIME * 60) {
                                    BleUtils.write(bleDevice, BleUtils.getTestWaterCommand(Contants.
                                            TEST_DURATION), new BleWriteCallback() {
                                        @Override
                                        public void onWriteSuccess(int current, int total, byte[] justWrite) {
                                            startNotify(bleDevice);
                                        }

                                        @Override
                                        public void onWriteFailure(BleException exception) {
                                            Toast.makeText(StartCourseActivity.this, getResources().
                                                    getString(R.string.fail_test_water), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    if (kProgressHUD != null && !kProgressHUD.isShowing()) {
                                        kProgressHUD.show();
                                    }
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (mVoltage > 3) {
                                                mLastCourseName = MyApplication.selectCourse.getName();
                                                MyApplication.runningCourse = MyApplication.selectCourse;
                                                Log.e("limit", "" + MyApplication.limitCount);
                                                bleWaterStart(mProgress);
                                            } else {
                                                dismiss();
                                                builder.setNegativeButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.dismiss();
                                                    }
                                                }).show();
                                            }
                                        }
                                    }, 3000);

                                } else {
                                    dismiss();
                                    new AlertDialog.Builder(StartCourseActivity.this)
                                            .setTitle(R.string.bluetooth_limit_title)
                                            .setMessage(R.string.bluetooth_limit_message)
                                            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    StartCourseActivity.this.finish();
                                                }
                                            });
                                }
                            }
                        }).create().show();
            } else {
                bleContinueCourse();
            }
        }
    }

    @Override
    public void setWaterData(BleDevice bleDevice, byte[] buffer) {
        super.setWaterData(bleDevice, buffer);
        String hexData = Utils.bytesToHexString(new byte[]{buffer[4]}).replaceAll(" ", "");
        mVoltage = Integer.parseInt(hexData, 16);
        Logger.d(TAG, "油水测试返回的电压值Voltage ：" + mVoltage);
    }

    public void getspDate() {
        date = BlEUtile.getCurrentTime();
    }

    private void blePauseCourse() {
        for (final BleDevice bleDevice : BleManager.getInstance().getAllConnectedDevice()) {
            BleUtils.write(bleDevice, BleUtils.getPauseCourseCommand(), new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    MySpUtils.putBoolean(MySpUtils.KEY_STAR_AUTO_INCREMENT, false);
                    dismiss();
                    EventBus.getDefault().post(new EventBean(Constants.EVENT_PAUSE_QUERY_SERVICE));
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
        }
    }

    private void bleStopCourse() {
        for (final BleDevice bleDevice : BleManager.getInstance().getAllConnectedDevice()) {
            BleUtils.write(bleDevice, BleUtils.getStopCourseCommand(), new BleWriteCallback() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    runStateTextView.setText(getResources().getString(R.string.un_runing));
                    runStateIamgeView.setImageResource(R.mipmap.run);
                    stopImageView.setEnabled(false);
                    pauseImageView.setEnabled(false);
                    startImageView.setEnabled(true);
                    MyApplication.bluetoothState = 0;
                    timeTextView.setText(countTime + " : 00");
                    EventBus.getDefault().post(new EventBean(Constants.EVENT_STOP_QUERY_SERVICE));
                    dismiss();
                    MySpUtils.putBoolean(MySpUtils.KEY_STAR_AUTO_INCREMENT, false);
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
        }
    }

    private void bleContinueCourse() {
        for (final BleDevice bleDevice : BleManager.getInstance().getAllConnectedDevice()) {
            BleUtils.write(bleDevice, BleUtils.getContinueCourseCommand(), new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    MySpUtils.putBoolean(MySpUtils.KEY_STAR_AUTO_INCREMENT, true);
                    dismiss();
                    EventBus.getDefault().post(new EventBean(Constants.EVENT_START_QUERY_SERVICE));
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
        }
    }

    private int countTime = 20;

    private void bleWaterStart(int finalWhich) {
        Courses courses = MyApplication.runningCourse;
        Integer timeone = courses.getTimeone();
        Integer timetwo = courses.getTimetwo();
        Integer timethree = courses.getTimethree();

        switch (timeTextView.getText().toString()) {
            case TIME_COUNT1://12
                timeone = (int) (12 * ((float) timeone / 20));
                timetwo = (int) (12 * ((float) timetwo / 20));
                timethree = (int) (12 * ((float) timethree / 20));
                countTime = 12;
                break;
            case TIME_COUNT2://16
                timeone = (int) (16 * ((float) timeone / 20));
                timetwo = (int) (16 * ((float) timetwo / 20));
                timethree = (int) (16 * ((float) timethree / 20));
                countTime = 16;
                break;
        }
        courses.setTimeone(timeone);
        courses.setTimetwo(timetwo);
        courses.setTimethree(timethree);
        for (final BleDevice bleDevice : BleManager.getInstance().getAllConnectedDevice()) {
            BleUtils.write(bleDevice, BleUtils.getWaterStartCommand(
                    courses, finalWhich, countTime), new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    //课程开始了，旧设备开始累计时间
                    EventBusUtil.sendEvent(new EventBean(Constants.EVENT_START_COURSE));
                    MySpUtils.putBoolean(MySpUtils.KEY_STAR_AUTO_INCREMENT, true);
                    startNotify(bleDevice);
                    EventBus.getDefault().post(new EventBean(Constants.EVENT_START_QUERY_SERVICE));
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        String voltage = "8v";
        if (mVoltageIndex == 0) {
            if (tvLow != null)
                voltage = tvLow.getText().toString();
        } else if (mVoltageIndex == 1) {
            if (tvMiddle != null)
                voltage = tvMiddle.getText().toString();
        } else {
            if (tvStrong != null)
                voltage = tvStrong.getText().toString();
        }
        MySpUtils.putString(MySpUtils.KEY_COURSE_VOLTAGE, voltage.split("v")[0]);
        MySpUtils.putString(MySpUtils.KEY_COURSE_TIME, String.valueOf(countTime));
    }

    private void bleChangVoltage(final int progress) {
        for (final BleDevice bleDevice : BleManager.getInstance().getAllConnectedDevice()) {
            BleUtils.write(bleDevice, BleUtils.getChangVoltageCommand(progress),
                    new BleWriteCallback() {
                        @Override
                        public void onWriteSuccess(int current, int total, byte[] justWrite) {

                        }

                        @Override
                        public void onWriteFailure(BleException exception) {

                        }
                    });
        }
    }


    public static void startAct(Context context, BleDevice bleDevice) {
        Intent intent = new Intent(context, StartCourseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable(Constants.BLE_DEVICE, bleDevice);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }


}
